package net.jiastudy.web.rest.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import net.jiastudy.biz.datasync.DeptImporter;
import net.jiastudy.core.exception.ServiceException;
import net.jiastudy.core.utils.UploadUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.plugins.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.jiastudy.biz.enums.DeptType;
import net.jiastudy.biz.sys.entity.Dept;
import net.jiastudy.biz.sys.service.DeptService;
import net.jiastudy.core.base.BaseController;
import net.jiastudy.core.common.validgroup.Create;
import net.jiastudy.core.common.validgroup.Update;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/depts")
@Api(value = "DeptController  部门")
public class DeptController extends BaseController{
	@Value("${upload.path.base}")
	private String basePath;
	@Resource
	private DeptService deptService;
	
	@RequestMapping(method = RequestMethod.GET)
	@ApiOperation(value = "分页检索部门列表", notes = "")
	public Page<Dept> page(DeptType type, @RequestParam Map<String, String> conditions,
			@PageableDefault(value = 50, sort = { "seq" }, direction = Sort.Direction.ASC) Pageable pageable) {
		Page<Dept> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		Sort sort = pageable.getSort();
		return deptService.pageDepts(page, type, conditions, sort);
	}
	
	@RequestMapping(path = "/checkcode", method = RequestMethod.GET)
	@ApiOperation(value = "检查部门编码是否重复", notes = "根据code检查是否重复,true为可用，false为不可用")
	public boolean checkCode(@RequestParam(required = true) String code, Long id) {
		return !deptService.checkCodeExists(code, id);
	}

	@RequestMapping(method = RequestMethod.POST)
	@ApiOperation(value = "新增部门", notes = "")
	public Dept create(@Validated({ Create.class }) @RequestBody Dept dept) {
		return deptService.createDept(dept);
	}

	@RequestMapping(path = "/{id}", method = RequestMethod.PUT)
	@ApiOperation(value = "编辑部门")
	public Dept edit(@PathVariable @ApiParam(name = "id", required = true) Long id,
			@Validated({ Update.class }) @RequestBody Dept dept) {
		dept.setId(id);
		return deptService.updateDept(dept);
	}

	@RequestMapping(path = "/{id}", method = RequestMethod.GET)
	@ApiOperation(value = "获取部门")
	public Dept get(@PathVariable @ApiParam(name = "id", required = true) Long id) {
		return deptService.getDept(id);
	}

	@RequestMapping(path = "/{id}/enable", method = RequestMethod.POST)
	@ApiOperation(value = "开启部门")
	public boolean enable(@PathVariable Long id) {
		return deptService.enableDept(id);
	}

	@RequestMapping(path = "/{id}/disable", method = RequestMethod.POST)
	@ApiOperation(value = "关闭部门")
	public boolean disable(@PathVariable Long id) {
		return deptService.disableDept(id);
	}
	
	@RequestMapping(path = "/list", method = RequestMethod.GET)
	@ApiOperation(value = "获取部门列表")
	public List<Dept> finds() {
		return deptService.findEnableDepts();
	}

	@RequestMapping(path = "/import", method = RequestMethod.POST)
	@ApiOperation(value = "导入部门")
	public boolean importDept(@RequestParam("file") MultipartFile file) {
		if (file.isEmpty() || file.getSize() == 0) {
			return true;
		}
		Date now = new Date();
		String fileName = file.getOriginalFilename();
		fileName = "/" + now.getTime() + fileName;

		String filePath = UploadUtil.TEMP_PATH + UploadUtil.makeFileDir(now);
		boolean bool = UploadUtil.mkdirs(basePath + filePath);
		if (!bool) {
			logger.error("创建目录失败，请检查权限");
			throw new ServiceException("500", "创建目录失败，请检查权限");
		}
		java.io.File dest = new java.io.File(basePath + filePath + fileName);
		try {
			file.transferTo(dest);
		} catch (IllegalStateException | IOException e) {
			logger.error("文件上传出错了：", e);
		}

		ImportParams params = new ImportParams();
		params.setHeadRows(1);
		ExcelImportResult<DeptImporter> list = ExcelImportUtil.importExcelMore(
				dest, DeptImporter.class, params);
		deptService.importDepts(list.getList());

		return true;
	}

	@RequestMapping(path = "/template", method = RequestMethod.GET)
	@ApiOperation(value = "下载导入模板")
	public void downloadTemplate(HttpServletResponse response) throws IOException  {
		List<DeptImporter> list = new ArrayList<>();
		DeptImporter deptImporter = new DeptImporter();
		deptImporter.setCode("001");
		deptImporter.setName("教务处");
		list.add(deptImporter);
		ExportParams params = new ExportParams();
		Workbook workbook = ExcelExportUtil.exportExcel(params, DeptImporter.class, list);

		UploadUtil.setFileDownloadHeader(response, "部门导入模板.xls");
		workbook.write(response.getOutputStream());
	}
}
